package com.uc.sdk;


import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端管理类
 */
public class ClientGroup {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //保存所有的tcp客户端
    private static Map<String,TcpClient> tcpClientMap = new ConcurrentHashMap<>();

    public static void add(Channel channel){
        channelGroup.add(channel);
    }

    public static void remove(Channel channel){
        channelGroup.remove(channel);
    }

    public static void add(String key,TcpClient client){
        tcpClientMap.put(key,client);
    }
    public static void remove(String key){
        tcpClientMap.remove(key);
    }
    public static TcpClient findClient(String key){
        return tcpClientMap.get(key);
    }
    /**
     * 获取通道属性
     * @param channel
     * @param key
     * @return
     */
    public static <T> T getAttr(Channel channel, String key){
        AttributeKey<T> attrKey = AttributeKey.valueOf(key);
        if(channel.hasAttr(attrKey)){
            Attribute<T> attr = channel.attr(attrKey);
            return attr.get();
        }else{
            return null;
        }
    }

    /**
     * 设置统统属性
     * @param channel
     * @param key
     * @param val
     * @param <T>
     */
    public static <T> void setAttr(Channel channel, String key, T val){
        AttributeKey<T> idAttrKey = AttributeKey.valueOf(key);
        Attribute<T> idAttr = channel.attr(idAttrKey);
        idAttr.set(val);
        channel.attr(idAttrKey);
    }
}
